/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.DAO;
import Server.BUS.StringUlti;
import Server.DTO.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;

/**
 *
 * @author Trung
 */
public class DatabaseAccess {
    
//    private DocumentBuilderFactory docFactory;
//    private DocumentBuilder docBuilder;
//    private Document doc;
    
    private Document doc = null;
    private DocumentBuilder builder = null;
    private DocumentBuilderFactory factory = null;
    
    public DatabaseAccess()
    {                
        factory = DocumentBuilderFactory.newInstance();
        
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(DatabaseAccess.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
    }    
    
     public void writeTableToFile(Table table, String path){
        doc = builder.newDocument();
         // Insert Root Table                
        Element root = (Element) doc.createElement("Table");
        root.setAttribute("name", table.getName());
        doc.appendChild(root);
        
//        Element columns = doc.createElement("Columns");
//        root.appendChild(columns);
        
        int colNumber = table.getColumns().size();
        for(int i = 0; i < colNumber; i++)
        {
            Element column = doc.createElement("Column");
            column.setAttribute("name", table.getColumns().get(i).getName());
            column.setAttribute("type", table.getColumns().get(i).getDataType());
            column.setAttribute("null", table.getColumns().get(i).isAllowNull() + "");
            column.setAttribute("primary", table.getColumns().get(i).isIsPrimaryKey() + "");
            
            int rowNumber = table.getColumns().get(i).getRowsList().size();
            for(int j = 0; j < rowNumber; j++)
            {
                Element row = (Element) doc.createElement("Row");
                row.setAttribute("id", String.valueOf(j+1));
                row.setAttribute("text", table.getColumns().get(i).getRowsList().get(j).getText());
                //row.setTextContent(table.getColumns().get(j).getRowsList().get(j).getText());
                
                column.appendChild(row);
            }
            
            root.appendChild(column);                  
        }
        
        // Normalizing the DOM
        doc.getDocumentElement().normalize();
        
        //Full path
        String fileName = "";
        for(int i = 0; i < path.length(); i++){
            if(path.charAt(i) == '.'){
                fileName = path;                
                DocumentUlti.writeDocToFile(fileName, doc);
                return;
            }
        }
        
        fileName = path + "\\" + table.getName() + ".xml";// + "-Design"   
        DocumentUlti.writeDocToFile(fileName, doc);        
    }
    
    public Table readTableFromFile(String filePath){//********
        doc = builder.newDocument();
        
        Table table = new Table();
        table.setPath(filePath);
        
        int begin = filePath.lastIndexOf("\\");
        int end = filePath.lastIndexOf(".");
        table.setName(filePath.substring(begin + 1, end));
        
        doc = DocumentUlti.parse(filePath);
        
        Element root = doc.getDocumentElement();
        table.setName(root.getAttribute("name"));
        
        //Columns
        NodeList colList = root.getChildNodes();//Columns list        
        int colNumber = colList.getLength();
        
        List<Column> lstColumns = new ArrayList<Column>();
        
        for(int i = 0; i < colNumber; i++)
        {
            Node colNode = colList.item(i);//*********   
            Column column = new Column(); 
            if(colNode.getNodeType() == Node.ELEMENT_NODE)
            {
                Element ele = (Element)colNode;                           
                column.setName(ele.getAttribute(("name")));
                column.setDataType((ele.getAttribute("type")));

                if(ele.getAttribute("null").compareTo("true") == 0){
                    column.setAllowNull(true);
                } else {
                    column.setAllowNull(false);
                }

                if(ele.getAttribute("primary").compareTo("true") == 0)
                {
                    column.setIsPrimaryKey(true);
                } 
                else {
                    column.setIsPrimaryKey(false);
                }
            }
            
            //Rows
            NodeList rowList = colList.item(i).getChildNodes();
            List<Row> lstRows = new ArrayList<Row>();  
            int rowNumber = rowList.getLength();
            for(int j = 0; j < rowNumber; j++)
            {
                Node rowNode = rowList.item(j);
                if(rowNode.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element rowElement = (Element)rowNode;
                    Row row = new Row();
                    row.setId(j + 1);
                    row.setText(rowElement.getAttribute("text"));
                    
                    lstRows.add(row);   
                    column.setRowsList(lstRows);
                }
            }
                                    
            lstColumns.add(column);
        }                
        
        table.setColumns(lstColumns);
        
        return table;
    }
    
    
    
    
}
